package com.huaxin.device.listener;

import com.huaxin.device.feignClients.SysFeignService;
import com.huaxin.device.models.DeviceAlarmConfig;
import com.huaxin.device.service.DeviceAlarmConfigService;
import com.huaxin.device.task.AlarmTaskScheduler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 启动监听
 */
@Component
@RequiredArgsConstructor
@Slf4j
public class StartupListener {

    private final DeviceAlarmConfigService deviceAlarmConfigService;
    private final AlarmTaskScheduler taskScheduler;
    private final SysFeignService sysFeignService;

    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationReady() {
        log.info("应用启动完成，开始加载报警检测任务...");

        // 从字典获取检测周期（如：0/30 * * * * ? 每30秒）
        String cronExpression = sysFeignService.getAlarmDetectInterval();

        List<DeviceAlarmConfig> configs = deviceAlarmConfigService.getAllEnabled();
        for (DeviceAlarmConfig config : configs) {
            taskScheduler.scheduleDevice(config.getDeviceId(), cronExpression);
        }

        log.info("共加载 {} 个设备的报警检测任务", configs.size());
    }

    /**
     * 重新加载报警任务（供配置变更时调用）
     */
    public void reloadAlarmTasks() {
        try {
            String cronExpression = sysFeignService.getAlarmDetectInterval();

            // 1. 取消所有旧任务
            taskScheduler.reloadAll();

            // 2. 延迟一小会，确保任务完全取消（可选）
            try {
                Thread.sleep(100); // 避免调度器未完全清理
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }

            // 3. 重新调度所有任务
            taskScheduler.rescheduleAll(cronExpression);

        } catch (Exception e) {
            log.error("重新加载报警任务失败", e);
        }
    }
}
